package cmd

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"strings"

	"gitee.com/qianyucc/secure-tool/util"

	"github.com/spf13/cobra"
)

// sha256Cmd represents the sha256 command
var sha256Cmd = &cobra.Command{
	Use:   "sha256",
	Short: "Get the hash of string or file through sha256 algorithm",
	Long:  `Get the hash of string or file through sha256 algorithm`,
	Run: func(cmd *cobra.Command, args []string) {
		var res string
		var err error
		if InputFile != "" {
			if res, err = ComputeFileWithSha256(InputFile); err != nil {
				fmt.Println(err)
				return
			}
		} else {
			var text string
			if text = util.ReadTextFromClipboard(); len(args) == 0 && text == "" {
				fmt.Println("invalid parameter numbers, please enter the string you want to get the hash")
				return
			}
			if len(args) > 0 {
				text = args[0]
			}
			res = ComputeStringWithSha256(text)
		}
		if IsUpperCase {
			res = strings.ToUpper(res)
		}
		util.PrintAndCopyTextToClipboardIgnoreError(res)
	},
}

// ComputeStringWithSha256 计算字符串的 sha256
func ComputeStringWithSha256(text string) (res string) {
	data := []byte(text)
	hash := sha256.New()
	hash.Write(data)
	sum := hash.Sum(nil)
	return hex.EncodeToString(sum[:])
}

// ComputeFileWithSha256 计算文件的 sha256
func ComputeFileWithSha256(inputFilePath string) (res string, err error) {
	var fp *os.File
	if fp, err = os.Open(inputFilePath); err != nil {
		return "", err
	}
	defer fp.Close()
	hash := sha256.New()
	buf := make([]byte, HASH_BLOCK_SIZE)
	if _, err := io.CopyBuffer(hash, fp, buf); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}

func init() {
	rootCmd.AddCommand(sha256Cmd)

	sha256Cmd.Flags().StringVarP(&InputFile, "file", "f", "", "The name of the file you are going to hash")
	sha256Cmd.Flags().BoolVarP(&IsUpperCase, "upperCase", "u", false, "Indicates whether the result is upper case")
}
